package kz.simplex.photobox.manager;

import java.io.File;
import java.io.IOException;

import javax.ejb.Remove;
import javax.ejb.Stateful;

import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Stateful
@Name("fileManager")
@Scope(ScopeType.APPLICATION)
@AutoCreate
public class FileManager implements IFileManager {
	private File uploadRoot;
	
	private String uploadRootPath;
	
	@Create
	public void create() {
		uploadRoot = (File)Component.getInstance("uploadRoot", ScopeType.APPLICATION);
		uploadRootPath = (String)Component.getInstance("uploadRootPath", ScopeType.APPLICATION);
	}
	
	public File getFileByPath(String path) {
		if (this.uploadRoot != null) {
			File result = new File(this.uploadRoot, path);
			try {
				final String resultCanonicalPath = result.getCanonicalPath();
				if (!resultCanonicalPath.startsWith(this.uploadRootPath)) {
					result = null;
				}
			}catch(IOException e) {
				result = null;
			}
			return result;
		}
		return null;
	}
	
	public File getFileByAbsolutePath(String path) {
		return new File(path);
	}
	
	@Destroy
	@Remove
	public void destroy() {}
}
